<template>
  <el-row>
    <el-card>
      <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item :label="$t('financeModule.repaymentCode.createType')">
          <el-select v-model="searchForm.type" multiple collapse-tags clearable :placeholder="$t('common.select')">
            <el-option
              v-for="item in $t('financeModule.repaymentCode.createTypes')"
              :key="item.desc"
              :label="item.value"
              :value="item.desc"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('financeModule.repaymentCode.tradeStatus')">
          <el-select v-model="searchForm.status" multiple collapse-tags clearable :placeholder="$t('common.select')">
            <el-option
              v-for="item in $t('financeModule.repaymentCode.tradeStates')"
              :key="item.desc"
              :label="item.value"
              :value="item.desc"
            />
          </el-select>
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-button :loading="addLoading" type="primary" @click="add">
        {{ $t('financeModule.repaymentCode.add') }}
      </el-button>
      <el-table
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        :stripe="true"
        style="width: 100%;margin-top: 10px"
      >
        <el-table-column
          prop="createTime"
          :label="tableText['createTime']"
          min-width="170"
        />
        <el-table-column
          prop="merchantOrderId"
          :label="tableText['transactionNumber']"
          min-width="180"
        />
        <el-table-column
          prop="orderNo"
          :label="tableText['loanOrderNo']"
          min-width="150"
        />
        <el-table-column
          prop="currentPeriod"
          :label="tableText['periodsNo']"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ scope.row['type'] === 1 ? '' : scope.row['currentPeriod'] + '/' + scope.row['totalPeriod'] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="paymentMethod"
          :label="tableText['payWay']"
          min-width="150"
        />
        <el-table-column
          prop="vaNumber"
          :label="tableText['repaymentCode']"
          min-width="150"
        />
        <el-table-column
          prop="effectTimeStr"
          :label="tableText['termValidity']"
          min-width="170"
        />
        <el-table-column
          prop="amount"
          :label="tableText['transactionAmount']"
          min-width="150"
        />
        <el-table-column
          prop="applyMoney"
          :label="tableText['transactionTime']"
          min-width="150"
        />
        <el-table-column
          prop="tel"
          :label="tableText['phoneNumber']"
          min-width="150"
        />
        <el-table-column
          prop="type"
          :label="tableText['createType']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ setValue(scope.row['type'], 'createTypes') }}
          </template>
        </el-table-column>
        <el-table-column
          prop="creator"
          :label="tableText['createPeople']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['creator'] ? scope.row['creator'] : $t('financeModule.repaymentCode.system') }}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          prop="status"
          :label="tableText['tradeStatus']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ setValue(scope.row['status'], 'tradeStates') }}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          :label="$t('common.operate.name')"
          min-width="250"
        >
          <template slot-scope="scope">
            <el-button v-if="scope.row['creator']" size="small" @click="copyLink(scope.row.id)">{{ tableText['operates']['copy'] }}</el-button>
            <el-button :loading="refreshLoading" size="small" @click="refreshStatus(scope.row.id)">
              {{ tableText['operates']['refreshStatus'] }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <repayment-code-dialog
      :show-dialog="editDialog"
      :choose-item="chooseItem"
      @change-dialog="changeDialog"
      @edit-success="editSuccess"
    />
  </el-row>
</template>

<script>
import { getRepaymentCode, vaNumberInfoCopy, needAddRepaymentCode, addRepaymentCode } from '@/api/order'
import RepaymentCodeDialog from '@/components/auth/repayment-code-dialog'
export default {
  name: 'RepaymentCode',
  components: {
    RepaymentCodeDialog
  },
  data() {
    return {
      addLoading: false,
      loading: false,
      tableData: [],
      tableText: {},
      totalNumber: 0,
      searchForm: this.params(),
      refreshLoading: false,
      editDialog: false,
      chooseItem: {
        orderNo: null,
        orderId: null,
        leftAmount: null,
        dealMoney: null
      }
    }
  },
  mounted() {
    this.tableText = this.$t('financeModule.repaymentCode.table')
    this.getData()
  },
  methods: {
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        orderId: this.$route.query.orderId ? this.$route.query.orderId : null,
        type: null,
        status: null
      }
    },
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    reset() {
      this.searchForm = this.params()
      this.getData()
    },
    getData() {
      this.loading = true
      const data = this.searchForm
      getRepaymentCode(data)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    add() {
      this.addLoading = true
      needAddRepaymentCode(this.$route.query.orderId)
        .then(res => {
          this.addLoading = false
          if (res.success) {
            this.choose(res.data)
            this.editDialog = true
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
          this.addLoading = false
        })
    },
    setValue(val, data) {
      const name = this.$t(`financeModule.repaymentCode.table.${data}`).filter(item => {
        return item.value === val
      })
      return (name && name[0] && name[0].desc) ? name[0].desc : ''
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    refreshStatus(id) {
      this.refreshLoading = true
      const data = this.searchForm
      data['id'] = id
      getRepaymentCode(data)
        .then(res => {
          this.refreshLoading = false
          if (res.success) {
            this.tableData.data.filter((value, key) => {
              if (value.id === id) {
                this.tableData.data.splice(key, 1, res.data[0])
                this.$message.success(this.$t('financeModule.repaymentCode.realyRefresh'))
              }
            })
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.refreshLoading = false
          this.$message.error(err.message)
        })
    },
    copyLink(id) {
      vaNumberInfoCopy(id)
        .then(res => {
          if (res.success) {
            const input = document.createElement('input')
            document.body.appendChild(input)
            input.setAttribute('value', res.data)
            input.select()
            if (document.execCommand('copy')) {
              document.execCommand('copy')
              this.$message.success(this.$t('collectDetail.copySuccess'))
            } else {
              this.$message.error(this.$t('collectDetail.copyError'))
            }
            document.body.removeChild(input)
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    changeDialog(param) {
      this.editDialog = param
      setTimeout(() => {
        this.choose({})
      }, 10)
    },
    choose(param) {
      this.chooseItem.orderNo = param.orderNo
      this.chooseItem.orderId = param.orderId
      this.chooseItem.leftAmount = param.leftAmount
      this.chooseItem.dealMoney = param.dealMoney
    },
    editSuccess() {
      this.getData()
    },
    copyTotalLink() {
      needAddRepaymentCode(this.$route.query.orderId)
        .then(res => {
          if (res.success) {
            const data = {
              orderNo: res.data.orderNo,
              orderId: res.data.orderId,
              leftAmount: res.data.leftAmount,
              dealMoney: res.data.leftAmount
            }
            addRepaymentCode(data)
              .then(request => {
                this.$emit('set-copy-loading')
                if (request.success) {
                  const input = document.createElement('input')
                  document.body.appendChild(input)
                  input.setAttribute('value', res.data)
                  input.select()
                  if (document.execCommand('copy')) {
                    document.execCommand('copy')
                    this.$message.success(this.$t('collectDetail.copySuccess'))
                  } else {
                    this.$message.error(this.$t('collectDetail.copyError'))
                  }
                  document.body.removeChild(input)
                } else {
                  this.$emit('set-copy-loading')
                  this.$message.error(request.message)
                }
              })
              .catch(err => {
                this.$message.error(err.message)
                this.$emit('set-copy-loading')
              })
          } else {
            this.$emit('set-copy-loading')
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card{
  margin: 10px;
}
</style>
